import { useState, useEffect, useRef, Fragment } from 'react'
import { Form, Input, Space, Button, MessagePlugin, Row, Col } from 'tdesign-react'
import AddDictionaryOption from './AddDictionaryOption'
import { ApiRequest, apis } from '@/service'
import styles from './index.module.less'

const { FormItem, useForm } = Form

const {
  insertDictionary,
} = apis.BMService.system

const AddDictionary = () => {

  const [dictionaryArrayLen, setDictionaryArrayLen] = useState(1)

  const [formRef] = useForm()

  const addDictionaryLen = () => {
    // todo
    // 校验选项是否已经填完整了
    let dictionaryArray = formRef.getFieldValue('dictionaryArray') as DictionaryListType || []
    dictionaryArray.push({ label: '', value: '' })
    setDictionaryArrayLen(dictionaryArrayLen + 1)
    formRef.clearValidate()
  }

  const delDictionaryLen = () => {
    let dictionaryArray = formRef.getFieldValue('dictionaryArray') as DictionaryListType || []
    dictionaryArray.pop()
    setDictionaryArrayLen(dictionaryArrayLen - 1)
    formRef.clearValidate()
  }

  const customValidador = () => {
    // return { validator: (value) => { console.log('value', value); return true }, message: '请输入内容'}
  }

  const validateDictionaryArray = (value: DictionaryListType) => {
    let validate = value ? true : false
    for (let i = 0; i < (value?.length || 0); i++) {
      if (!value[i]?.label || !value[i]?.value) {
        validate = false
        break
      }
    }
    return validate
  }

  const onSubmit = (context: any) => {
    console.log('context', context)
    // 校验成功则运用if逻辑
    if (context.validateResult === true) {
      let params = {
        ...context.fields,
      }
      ApiRequest({ api: insertDictionary, params: params }).then((res: ResponseDataType) => {
        const { code = -1, data = [], note = '' } = res
        if (code > 0) {
          formRef.reset()
          MessagePlugin.success({
            content: note || '提交成功',
            placement: 'top-right',
            duration: 2000})
        } else {
          MessagePlugin.error({
            content: note || '提交失败',
            placement: 'top-right',
            duration: 2000})
        }
      })
    } else {
      MessagePlugin.error({
        content: context.firstError,
        placement: 'top-right',
        duration: 2000})
    }
  }

  const onReset = () => {
    setDictionaryArrayLen(1)
  }

  return <div className={'content-wrapper'}>
    <Form
      form={formRef}
      className='aio-form'
      onSubmit={onSubmit}
      onReset={onReset}
      labelAlign={'top'}
      resetType='initial'
    >
      <Row gutter={16}>
        <Col span={6}>
          {/* 字典名称 */}
          <FormItem
            label="字典名称"
            name="dictionaryName"
            rules={[{ required: true, message: '请输入字典名称' }]}
          >
            <Input
              maxlength={20}
              placeholder="请输入字典的名称"
              clearable
            />
          </FormItem>
        </Col>
        <Col span={6}>
          {/* 字典值 */}
          <FormItem
            label="字典值"
            name="dictionaryValue"
            rules={[{ required: true, message: '请输入字典值'}]}
          >
            <Input
              maxlength={80}
              placeholder="请输入字典的值，英文"
              clearable
            />
          </FormItem>
        </Col>
      </Row>
        {/* 字典数据 */}
        <FormItem
          className={styles.addDictionaryOptionsFormItem}
          label="字典选项"
          name="dictionaryArray"
          rules={[{ required: true, message: '请填写字典项内容'}, { validator: validateDictionaryArray, message: '请完成所有字典项内容'}]}
        >
          {Array(dictionaryArrayLen).fill(undefined).map((_: any, index: number) => {
            return <AddDictionaryOption index={index} key={index} />
          })}
        </FormItem>
      <Button onClick={addDictionaryLen} style={{marginRight: 20}}>添加字典项</Button>
      <Button onClick={delDictionaryLen}>减少字典项</Button>
      <Row gutter={16}>
        <Col span={6} style={{ textAlign: 'right' }}>
          <Button type="submit" theme="primary">
            提交
          </Button>
        </Col>
        <Col span={6} style={{ textAlign: 'left' }}>
          <Button type="reset" theme="default">
            重置
          </Button>
        </Col>
      </Row>
    </Form>
  </div>
}

export default AddDictionary
